import {
  logout,
  getInfo
} from '@/api/user'
import {
  getToken,
  setToken,
  removeToken
} from '@/utils/auth'
import {
  resetRouter
} from '@/router'
import {
  login,
  getMenu,
  getData
} from 'menucontrol'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    // roles: "", //新增
    menu: null,
    buttons: {},
    isDirector:false,//是否主管
    isFinancial:false,//是否财务
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  // 新增
  // SET_ROLES: (state, roles) => {
  //   state.roles = roles
  // },
  SET_MENU: (state, menu) => {
    state.menu = menu
  },
  SET_BTN: (state, btn) => {
    state.buttons = btn
  },
  SET_DIR:(state,bol)=>{
    state.isDirector = bol
  },
  SET_financial:(state,bol)=>{
    state.isFinancial = bol
  }
}

const actions = {
  // user login
  // 登录验证
  login({ 
    commit
  }, userInfo) {
    const {
      account,
      password
    } = userInfo
    return new Promise((resolve, reject) => {
      login({
        username: account.trim(),
        password: password,
        app_id: process.env.VUE_APP_ADMIN_APP_ID
      }).then(response => {
        const {
          data
        } = response
        commit('SET_TOKEN', data.accessToken) //把token存入state
        localStorage.setItem("refreshToken", data.refreshToken)
        localStorage.setItem("SET_NAME", data.name)
        localStorage.setItem("SET_ACCOUNT", data.account)
        //判定权限
        if(data.menu.buttons.director){
          commit('SET_DIR',true)
          console.log('欢迎主管登陆');
        }
        if(data.menu.buttons.financial){
          commit('SET_financial',true)
          console.log('欢迎财务登陆');
        }
        // app_id: '503dbcd06e6643b7ea9fe44647bfb2be'//测试
        // app_id: '1baddf9875c66f775d4036213d2e9674'//生产
        // let routers = getMenu(data.menu.menu)
        // routers.push({ path: '*', redirect: '/404', hidden: true })
        // commit('SET_MENU', routers)//把menu存入state
        //  router.addRoutes(routers)
        // window.localStorage.setItem('menu',JSON.stringify(routers) ) //菜单存本地
        setToken(data.accessToken) //调用utils下的auth 使用cookie存令牌
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // login({
  //   commit
  // }, userInfo) {
  //   const {
  //     account,
  //     password
  //   } = userInfo
  //   return new Promise((resolve, reject) => {
  //     login({
  //       account: account.trim(),
  //       password: password
  //     }).then(response => {
  //       const {
  //         data
  //       } = response
  //       sessionStorage.setItem("refreshToken", data.refreshToken)
  //       commit('SET_TOKEN', data.accessToken) //把token存入state
  //       setToken(data.accessToken) //调用utils下的auth 使用cookie存令牌
  //       resolve()
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },
  getMenus({
    commit
  }) {
    return new Promise((resolve, reject) => {
      getData().then(res => {
        let routers = getMenu(res.data.menu)
        // let buttons = formateButton(res.data.buttons)
        routers.push({
          path: '*',
          redirect: '/404',
          hidden: true
        })
        commit('SET_MENU', routers) //把menu存入state
        commit('SET_BTN', res.data.buttons) //把按钮权限存入state
                //判定权限
                if(res.data.buttons.director){
                  console.log('欢迎主管登陆');
                  commit('SET_DIR',true)
                }
                if(res.data.buttons.financial){
                  console.log('欢迎财务登陆');
                  commit('SET_financial',true)
                }
        resolve()

      })
    })
  },
  // get user info
  getInfo({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const {
          data
        } = response
        sessionStorage.setItem("data", JSON.stringify(data))
        if (!data) {
          return reject('验证失败，请重新登录')
        }

        const {
          name,
          avatar
        } = data

        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  //获取路由表
  getAntRouter({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      DongtRouter().then(response => { //请求路由表 把list结构出来
        const {
          list
        } = response.data
        if (!list) {
          reject('验证失败，请重新登录')
        }
        const arr = []
        for (let i = 0; i < list.length; i++) {
          const arrOne = list[i];
          arr.push(arrOne.permissionname)
        }
        const roles = arr
        // roles must be a non-empty array
        if (!roles || roles.length <= 0) {
          reject('DongtRouter:角色必须是非空数组!')
        }
        // debugger
        commit('SET_ROLES', roles)
        resolve(roles)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      // logout(state.token).then(() => {
      removeToken() // must remove  token  first
      resetRouter()
      commit('RESET_STATE')
      resolve()
    })
    // .catch(error => {
    //   reject(error)
    // })
    // })
  },

  // remove token
  resetToken({
    commit
  }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      commit('SET_ROLES', [])
      resolve()
    })
  },

  // async changeRoles({
  //   commit,
  //   dispatch
  // }, role) {
  //   const token = role + '-token'
  //   commit('SET_TOKEN', token)
  //   setToken(token)

  //   const roles = await dispatch('DongtRouter')
  //   resetRouter()
  //   // generate accessible routes map based on roles
  //   const accessRoutes = await dispatch('permission/generateRoutes', roles, {
  //     root: true
  //   })
  //   // dynamically add accessible routes
  //   router.addRoutes(accessRoutes)

  //   // reset visited views and cached views
  //   dispatch('tagsView/delAllViews', null, {
  //     root: true
  //   })
  // }
}


export default {
  namespaced: true,
  state,
  mutations,
  actions
}
